/*

Copyright (C) 2007 Thomas Geiger (tom.geiger@gmail.com)

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*/

#include "globuscpp/CredManager.h"
#include "globuscpp/URL.h"
#include "globuscpp/XIOClient.h"

using namespace globus_common;
using namespace globus_xio;


#include "gt-ls.h"

static void usage() {
	error("gt_save('URL', 'format', 'varname')");
}

DEFUN_DLD(gt_save, 
          args, 
          , 
          "Save Octave variables to a Globus file resource."
          ) 
{	
	int argNum;
	string urlPath;
	string fileFormat = "ascii";
	load_save_format format;	
	stringstream output;
	octave_value_list retval;
	
	// arg(0) => url
	// arg(1) => file format
	// ...
	argNum = args.length();
	if (argNum <= 1)  {
		usage();	
		return octave_value(false);
	}
	
	// check for existing certificate
	CredManager credMgr;
	credMgr.getUserCertFile();
	if ( !credMgr.hasCredential() ) {
		cerr << "No valid credentials found." << endl;	
		return octave_value(false);
	} 
	
	// check this conversion	
	urlPath = args(0).string_value();
	if (argNum > 1) {
		fileFormat = args(1).string_value();	
	}
			
	// determine file format
	if (! set_format(format, fileFormat) ) {
		cerr << "Invalid file format: " << fileFormat << endl;
		return octave_value(false);	
	}
	
	// construct url
	URL* g_url = URL::Create(urlPath);
	if (g_url == NULL) {
		return octave_value(false);	
	}
	
	// initialize client
	XIOClient* client = new XIOClient();
	client->setUrl(g_url);
		
	// writes ov into stream
	save_data(output, format, args);
	
	output.flush();
	output.seekg(0);
	
	bool success = client->send(output);		

	if (!success) {
		cerr << "Could not send data. Network error?" << endl;
		return octave_value(false);	
	}
	
	delete client;
	delete g_url;

	return octave_value(true);	
}
